package com.leef.createPay.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryBeanOne",//配置连接工厂 entityManagerFactory
        transactionManagerRef = "platformTransactionManagerOne", //配置 事物管理器  transactionManager
        basePackages = {"com.leef.createPay.dao.one"}
)
public class JpaConfigOne {
    @Resource(name = "db1")
    DataSource ds1;

    @Autowired
    JpaProperties jpaProperties;

 /*   @Bean()
    @Primary
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryBeanOne(builder).getObject().createEntityManager();
    }*/

    @Bean(name = "entityManagerFactoryBeanOne")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBeanOne(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(ds1)
                .properties(jpaProperties.getProperties())
                .packages("com.leef.createPay.domain.one")
                //持久化单元名称，当存在多个EntityManagerFactory时，需要制定此名称
                .persistenceUnit("pu1")
                .build();
    }
    @Bean(name = "platformTransactionManagerOne")
    public PlatformTransactionManager platformTransactionManagerOne(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean factoryOne = entityManagerFactoryBeanOne(builder);
        return new JpaTransactionManager(factoryOne.getObject());
    }

    @Bean(name = "entityManagerOne")
    @Primary
    public EntityManager entityManager(EntityManagerFactoryBuilder builder){
        return entityManagerFactoryBeanOne(builder).getObject().createEntityManager();

    }


}

